/*
 *  Copyright (c) 2011, StripBandunk and/or its affiliates. All rights reserved.
 * 
 *       http://stripbandunk.com/
 * 
 *  STRIPBANDUNK PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package stripbandunk.tutorial.treetabledemo.util;

import java.util.Random;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import stripbandunk.tutorial.treetabledemo.entity.Category;
import stripbandunk.tutorial.treetabledemo.entity.Product;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author echo
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void init() {
        Session session = getSessionFactory().openSession();
        session.beginTransaction();

        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            Category category = new Category("Category " + i);
            session.save(category);
            for (int j = 0; j < 100; j++) {
                Product product = new Product("product" + i + "" + j, "Product " + j + " in Category " + i, random.nextLong(), category);
                session.save(product);
            }
        }

        session.getTransaction().commit();
        session.close();
    }
}
